<template>
    <div class="home">
        <el-card>
            <!-- 卡片的头部区 -->
            <div slot="header" class="clearfix">
                演示用户的增删改查
            </div>

            <!-- 搜索框 -->
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input
                        placeholder="请输入关键词"
                        v-model="keyword"
                        clearable
                        @clear="handleSearchInputClear"
                    >
                        <el-button
                            slot="append"
                            icon="el-icon-search"
                            @click="getList"
                        ></el-button>
                    </el-input>
                </el-col>

                <el-col :span="4">
                    <el-button
                        type="primary"
                        icon="el-icon-plus"
                        @click="addUserDialogVisible = true"
                        >添加</el-button
                    >
                </el-col>
            </el-row>

            <!-- 卡片的内容区 -->
            <el-table :data="list" border style="width: 100%">
                <el-table-column prop="id" label="ID"> </el-table-column>

                <el-table-column prop="username" label="用户名">
                </el-table-column>

                <el-table-column prop="password" label="账户密码">
                </el-table-column>

                <el-table-column prop="mobile" label="手机号">
                </el-table-column>

                <el-table-column prop="email" label="邮箱"> </el-table-column>

                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button
                            icon="el-icon-edit"
                            size="mini"
                            type="primary"
                            plain
                            @click="handleEditUser(scope.row)"
                            >编辑</el-button
                        >
                        <el-button
                            icon="el-icon-delete"
                            size="mini"
                            type="danger"
                            plain
                            @click="handleDeleteUser(scope.row)"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination
                @size-change="getList"
                @current-change="getList"
                :current-page.sync="pagenum"
                :page-sizes="[1, 2, 5, 10, 50, 100]"
                :page-size.sync="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
            >
            </el-pagination>
        </el-card>

        <!-- 用户输入弹框 -->
        <!-- visible 弹框是否显示，如果使用 .sync 语法糖，那么就能同步属性值了 -->
        <el-dialog
            title="添加用户"
            :visible.sync="addUserDialogVisible"
            width="65%"
        >
            <!-- model 是表单内的数据对象 -->
            <!-- rules 指定表单校验规则，他也是一个对象 -->
            <el-form
                :model="addUserForm"
                :rules="addUserFormRules"
                ref="addUserFormRef"
                label-position="top"
            >
                <!-- label 就是指定输入框代表的名称 -->
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addUserForm.username"></el-input>
                </el-form-item>

                <el-form-item label="密码" prop="password">
                    <el-input v-model="addUserForm.password"></el-input>
                </el-form-item>

                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="addUserForm.mobile"></el-input>
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addUserForm.email"></el-input>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="addUserDialogVisible = false"
                    >取 消</el-button
                >
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    created() {
        this.getList();
    },
    data() {
        return {
            list: [],
            pagenum: 1,
            pagesize: 10,
            total: 0,
            keyword: "",
            addUserDialogVisible: false,
            addUserForm: {
                username: "",
                password: "",
                mobile: "",
                email: "",
            },
            addUserFormRules: {
                username: [
                    {
                        required: true,
                        message: "请输入用户名",
                        trigger: "change",
                    },
                ],
                password: [
                    {
                        required: true,
                        message: "请输入用户密码",
                        trigger: "change",
                    },
                ],
                mobile: [
                    {
                        validator: (rule, value, callback) => {
                            if (!/^1[3579]\d{9}$/.test(value)) {
                                callback(new Error("手机号格式不正确"));
                                return;
                            }
                            callback();
                        },
                    },
                ],
                email: [
                    {
                        validator: (rule, value, callback) => {
                            if (!/^\w+@\w+\.com$/.test(value)) {
                                callback(new Error("邮箱格式不正确"));
                                return;
                            }
                            callback();
                        },
                    },
                ],
            },
        };
    },
    methods: {
        async getList() {
            const res = await this.$http.get(`/users`, {
                params: {
                    pagenum: this.pagenum,
                    pagesize: this.pagesize,
                    keyword: this.keyword,
                },
            });
            this.list = res.data.list;
            this.total = res.data.total;
        },
        handleSearchInputClear() {
            this.keyword = "";
            this.getList();
        },
        addUser() {
            // console.log("this.addUserForm", this.addUserForm);
            this.$refs.addUserFormRef.validate(async (isOk) => {
                // isOk 表示表单校验是否成功，如果成功了，就返回 true，如果失败，返回 false
                // console.log("isOk", isOk);
                // 如果校验通过了，那么就发送请求给 Koa 服务器，保存数据到数据库中
                if (isOk) {
                    const res = await this.$http.post(
                        "/users",
                        this.addUserForm
                    );

                    // console.log("res", res);
                    if (res.code !== 201) {
                        this.$notify.error({
                            title: res.message,
                        });
                    } else {
                        // 关闭这个弹框
                        this.addUserDialogVisible = false;
                        // 刷新列表
                        this.getList();
                        // 重置表单
                        this.$refs.addUserFormRef.resetFields();
                    }
                }
            });
        },
        handleDeleteUser(row) {
            this.$confirm(
                `此操作将永久删除 ${row.username} 用户, 是否继续?`,
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }
            )
                .then(async () => {
                    // console.log("row", row);
                    const res = await this.$http.delete(`/users/${row.id}`);
                    if (res.code !== 204) {
                        this.$notify.error({
                            title: res.message,
                        });
                        return;
                    }
                    // 刷新列表
                    this.getList();
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除",
                    });
                });
        },
        handleEditUser(row) {
            console.log("row", row);
        },
    },
};
</script>

<style lang="less">
.home {
    height: 100%;
    .el-table,
    .el-pagination {
        margin-top: 15px;
    }
}
</style>
